<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="所属项目">
              <a-select show-search :filter-option='filterOption' @change="selectAreaByProjectId"
                        defaultValue="" v-model="queryParam.projectId">
                <a-select-option v-for="item in projectSelectOption" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="所属区域">
              <a-select
                defaultValue="" v-model="queryParam.areaId">
                <a-select-option v-for="item in areaSelectOption" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="3" :sm="8">
            <a-form-item label="姓名">
              <a-input placeholder="请输入姓名" v-model="queryParam.userName"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="4" :sm="8">
              <a-form-item label="手机号">
                <a-input placeholder="请输入手机号" v-model="queryParam.mobile"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="8">
              <a-form-item label="证件类型">
                <a-input placeholder="请输入证件类型" v-model="queryParam.certType"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="8">
              <a-form-item label="性别">
                <a-input placeholder="请输入性别" v-model="queryParam.gender"></a-input>
              </a-form-item>
            </a-col>

          </template>

          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="开始日期" v-model='queryParam.opTime_begin' @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="结束日期" v-model='queryParam.opTime_end'  @change="onChangeEndTime"/>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" style="margin-right: 10px">新增</a-button>
      <!--      <a-button @click="handleBatchAdd" type="primary" icon="plus">批量新增</a-button>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
<!--          <a-menu-item key="1" @click="grandBatchUser">-->
<!--            <a-icon type="delete"/>-->
<!--            授权-->
<!--          </a-menu-item>-->
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a-divider type="vertical"/>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical"/>
             <a @click="handleGrand(record)">门禁授权</a>
          <a-divider type="vertical"/>


                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>

        </span>
        <span slot="gender" slot-scope="record">
          <span v-if="record===1">男</span>
          <span v-if="record===2">女</span>
        </span>


      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>
    <user-modal-detail ref="modalFormDetail" @ok="modalFormOk"></user-modal-detail>
    <area-tree ref="modalAreaTree" @ok="modalFormOk"></area-tree>
    <user-batch-modal ref="userBatchModal" @ok="modalFormOk"></user-batch-modal>
    <user-device-modal ref="userDeviceModal" @ok="modalFormOk"></user-device-modal>
  </a-card>
</template>

<script>
import UserModal from './modules/UserModal'
import UserModalDetail from './modules/UserModalDetail'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, downFile, getAction} from '@/api/manage'
import {filterObj} from '@/utils/util'
import AreaTree from './modules/AreaTree'
import UserBatchModal from '@views/passage/userstaff/modules/UserBatchModal'
import UserDeviceModal from '@views/passage/userstaff/modules/UserDeviceModal'

export default {
  name: "UserList",
  mixins: [JeecgListMixin],
  components: {
    UserModal,
    UserModalDetail,
    AreaTree,
    UserBatchModal,
      UserDeviceModal,
  },
  data() {
    return {
      description: '人员管理页面',

      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '所属项目',
          align: "center",
          dataIndex: 'projectName'
        },
        {
          title: '姓名',
          align: "center",
          dataIndex: 'userName'
        },

        {
          title: '人员类型',
          align: "center",
          dataIndex: 'projectUserTypeName'
        },
        {
          title: '手机号',
          align: "center",
          dataIndex: 'mobile'
        },

        {
          title: '所在区域',
          align: "center",
          dataIndex: 'areaName'
        },

        {
          title: '所在房屋',
          align: "center",
          customRender: function (t, r, index) {
            let locateName = ''
            if (r.projectName != null) {
              locateName = r.projectName
            }
            if (r.areaName != null) {
              locateName += '-'+ r.areaName
            }
            if (r.buildingName != null) {
              locateName += '-'+ r.buildingName
            }
            if (r.unitName != null) {
              locateName +='-'+ r.unitName
            }
            if (r.floorName != null) {
              locateName +='-'+ r.floorName
            }
            if (r.houseName != null) {
              locateName +='-'+ r.houseName
            }
            return locateName;
          }
        },

        {
          title: '部门组织',
          align: "center",
          dataIndex: 'departmentName'
        },

        {
          title: '照片',
          width: 80,
          align: "center",
          dataIndex: 'imgUrl',
          customRender: (record) => {
            let r = record
            return (
              <img
                style="max-width:35px;max-height:35px;min-height:20px;min-width:20px;text-align:center;cursor:pointer;border:1px #BFBFBF solid;padding: 2px 2px 2px 2px;background-color:white;"
                preview={r}
                src={record}
              ></img>
            )
          }
        },
        {
          title: '证件类型',
          align: "center",
          visible: false,
          dataIndex: 'certType'
        },
        {
          title: '性别',
          align: "center",
          visible: false,
          dataIndex: 'gender',
          scopedSlots: {customRender: 'gender'}
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime'
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark'
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
        }
      ],

      projectSelectOption: [],
      areaSelectOption: [],
      url: {
        list: "/user/user/list",
        delete: "/user/user/delete",
        deleteBatch: "/user/user/deleteBatch",
        exportXlsUrl: "user/user/exportXls",
        importExcelUrl: "user/user/importExcel",
        projectInfo: "projectUserType/projectUserType/projectInfo",
        AreaInfos: "/area/getAreaList",
        grandBatchUser: "/user/user/grandBatchUser"
      },
      queryParam: {
        "opTime_begin": "",
        "opTime_end": "",
        "type": "-1",
        "areaId": "",
        "projectId": ""

      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },

  created() {
    this.loadProjectInfo();
    this.keyupEnter();
  },
  methods: {
    filterOption(input, option) {
      input = String(input)
      return (
        option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      )
    },
    searchReset: function () {
      this.queryParam = {
        "opTime_begin": "",
        "opTime_end": "",
      }
      this.areaSelectOption = []
      this.loadData(1);
    },
    grandBatchUser() {
      let ids = this.selectedRowKeys
      let idstr = "";
      ids.forEach((id) => {
        idstr += id + ","
      })

      getAction(this.url.grandBatchUser, {userIds: idstr}).then(
        (res) => {
          if (res.success) {
            this.$message.success("批量授权成功")
          } else {
            this.$message.warning(res.message)
          }
        }
      )
    },

    loadProjectInfo() {
      const _this = this
      this.loading = true;
      getAction(this.url.projectInfo).then(function (resp) {
        _this.projectSelectOption = resp.result
      })
      this.loading = false;
    },
    selectAreaByProjectId(projectId) {
      const _this = this
      this.queryParam.areaId=""
      getAction(this.url.AreaInfos, {projectId: projectId}).then(function (resp) {
        _this.areaSelectOption = resp.result
      })
    },
    handleAdd() {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增"
    },
    handleBatchAdd() {
      this.$refs.userBatchModal.add()
      this.$refs.userBatchModal.title = '批量新增'
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑"
    },
    handleDetail(record) {
      this.$refs.modalFormDetail.edit(record)
      this.$refs.modalFormDetail.title = "详情"
    },
    handleGrand(record) {
      this.$refs.modalAreaTree.showIt(record.id,record.projectId)
    },
      showHandleGrand(record){
        this.$refs.userDeviceModal.showIt(record);
      },
    handleExportXls(fileName) {

      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;
      let opDesc = this.queryParam.opDesc;
      let dayTime = startTime;
      if (startTime == "") {
        this.$message.error("请选择导出开始日期");
        return
      }
      if (endTime == "") {
        this.$message.error("请选择导出结束日期");
        return
      }
      if (startTime != "" && endTime != "") {
        if (startTime != endTime) {
          this.$message.error("仅支持1天数据导出,请选择导出日期");
          return
        }
      }
      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {...this.queryParam};
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
    },
    onChangeStartTime(date, dateString) {
      this.queryParam.opTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.opTime_end = dateString;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }

      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success && res.result != null) {
          this.dataSource = res.result.records;
          console.log(this.dataSource)
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;

      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }

      this.loadData(1);
    },

    getQueryParams() {

      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      return filterObj(param);
    },

    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        let ids = "";
        for (let a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ",";
        }
        let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {

            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }

            });

          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      this.loading = true;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>